package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 *
 * date:2022/9/20 14:07
 * 描述：
 **/
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderFeignClient orderFeignClient;

    //  获取到所有的秒杀商品数据
    @GetMapping("findAll")
    public Result findAll(){
        //  获取到秒杀列表
        List<SeckillGoods> seckillGoodsList = seckillGoodsService.findAll();
        //  返回数据
        return Result.ok(seckillGoodsList);
    }

    //  /api/activity/seckill/getSeckillGoods/{skuId}
    @GetMapping("getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId){
        //  获取到秒杀列表
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        //  返回数据
        return Result.ok(seckillGoods);
    }
    
    //  抢购码：
    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        //  MD5(userId)
        String userId = AuthContextHolder.getUserId(request);
        //  在秒杀开始以后，结束之前
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoods(skuId);
        if (seckillGoods!=null){
            //  判断
            Date currentTime = new Date();
            if (DateUtil.dateCompare(seckillGoods.getStartTime(),currentTime) && DateUtil.dateCompare(currentTime,seckillGoods.getEndTime())){
                //  生成抢购码
                String skuIdStr = MD5.encrypt(userId);
                //  返回抢购码
                return Result.ok(skuIdStr);
            }
        }
        return Result.fail().message("生成抢购码失败.");
    }

    //  预下单：this.api_name + '/auth/seckillOrder/' + skuId + '?skuIdStr=' + skuIdStr
    //  /auth/seckillOrder/{skuId}?skuIdStr=xxx
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,HttpServletRequest request){
        //  获取抢购码
        String skuIdStr = request.getParameter("skuIdStr");
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  调用服务层方法.
        return this.seckillGoodsService.seckillOrder(skuId,skuIdStr,userId);
    }

    //  /auth/checkOrder/' + skuId
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        /*
            1.  验证缓存中是否有用户Id
            2.  判断用户是否有预下单 ---> 抢购成功 去下单
            3.  判断用户是否真正下过订单 ---> 抢购成功 我的订单
            4.  校验一下状态位
         */
        //  调用服务层方法.
        return this.seckillGoodsService.checkOrder(skuId,userId);

    }

    //  秒杀结算页。
    @GetMapping("/auth/trade")
    public Result authTrade(HttpServletRequest request){
        //  声明一个map 集合
        HashMap<String, Object> hashMap = new HashMap<>();
        //  获取到用户Id
        //  userAddressList， detailArrayList， totalNum， totalAmount
        String userId = AuthContextHolder.getUserId(request);
        //  远程调用收货地址列表.
        List<UserAddress> userAddressList = this.userFeignClient.findUserAddressListByUserId(userId);

        //  获取到订单明细 获取到秒杀商品赋值给订单明细  detailArrayList -- orderDetail
        //  我们有预下单数据： OrderRecode
        OrderRecode orderRecode = (OrderRecode) this.redisTemplate.opsForHash().get(RedisConst.SECKILL_ORDERS, userId);
        //  判断
        if (orderRecode == null){
            return Result.fail().message("获取预下单数据失败.");
        }
        //  获取到秒杀商品
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();
        //  赋值给订单明细
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuId(seckillGoods.getSkuId());
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setSkuNum(orderRecode.getNum());

        ArrayList<OrderDetail> detailArrayList = new ArrayList<>();
        detailArrayList.add(orderDetail);

        hashMap.put("userAddressList",userAddressList);
        hashMap.put("detailArrayList",detailArrayList);
        hashMap.put("totalNum","1");
        hashMap.put("totalAmount",seckillGoods.getCostPrice());

        //  存储数据 map
        return Result.ok(hashMap);
    }

    //  提交订单控制器 /auth/submitOrder
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        //  获取userId
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));

        //  调用服务层方法.  保存到数据库中 orderInfo + orderDetail;
        Long orderId = this.orderFeignClient.submitSeckillOrder(orderInfo);
        if (orderId==null){
            //  提示信息.
            return Result.fail().message("下单失败.");
        }

        //  将真正下单保存到缓存中.
        //  hset key field value key = SECKILL_ORDERS_USERS = "seckill:orders:users";  field = userId  value = orderId
        this.redisTemplate.opsForHash().put(RedisConst.SECKILL_ORDERS_USERS,userId,orderId.toString());
        //  删除预下单数据
        //              Boolean result = this.redisTemplate.opsForHash().hasKey(RedisConst.SECKILL_ORDERS, userId);
        //  del RedisConst.SECKILL_ORDERS
        //  hdel RedisConst.SECKILL_ORDERS field
        this.redisTemplate.opsForHash().delete(RedisConst.SECKILL_ORDERS,userId);
        //  返回数据.
        return Result.ok(orderId);
    }


}